package com.example.demo.service.serviceImp;

import com.example.demo.entity.Token;
import com.example.demo.entity.User;
import com.example.demo.mapper.TokenMapper;
import com.example.demo.service.LoginService;
import com.example.demo.util.TokenUtil;
import com.example.demo.util.UUidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LoginServiceImp implements LoginService {
    @Autowired
    private TokenMapper tokenMapper;

    @Override
    public String getToken(User user){
        //根据数据库的用户信息查询Token
        Token token1 = new Token();
        token1.setUserId(user.getUid());
        Token token = tokenMapper.findByUserId(token1);
        //为生成Token准备
        String TokenStr = "";
        Date date = new Date();
        int nowtime = (int) (date.getTime() / 1000);
        //生成Token
        TokenStr = TokenUtil.getToken(user, date);
        if (null == token) {
            //第一次登陆
            token = new Token();
            token.setToken(TokenStr);
            token.setCreateTime(nowtime);
            token.setUserId(user.getUid());
            token.setId(UUidUtil.getUUid());
            tokenMapper.insert(token);
        }else{
            //登陆就更新Token信息
            TokenStr = TokenUtil.getToken(user, date);
            token.setToken(TokenStr);
            token.setCreateTime(nowtime);
            tokenMapper.updateById(token);
        }
        return TokenStr;
    }

    @Override
    public int logout(String token) {
        return tokenMapper.deleteByToken(token);
    }

    @Override
    public User selectCurrentUser(String token) {

        return tokenMapper.selectCurrentUser(token);
    }

}
